package com.zzyl.serve.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.mapper.DeviceDataMapper;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.service.IDeviceService;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 设备管理Service业务层处理
 * 
 * @author liuyp
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        //1. 向华为云IoTDA平台发请求，查询产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-同步产品列表失败");
        }

        //2. 将产品列表缓存到Redis里：使用string类型存储，先确定缓存的key
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        //1. 从缓存里获取数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (jsonStr == null || "".equals(jsonStr)) {
            return Collections.emptyList();
        }

        //2. 将json字符串转换成ProductVo集合，返回给客户端
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {
        //1. 先校验
        // 1.1 校验设备标识码是否已经存在：根据标识码查询一下，如果有就说明已经存在了
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId());
        Device device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备标识码已存在");
        }
        // 1.2 校验设备名称是否已经存在：根据设备名称查询一下，如果有就说明已经存在了
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName());
        device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备名称已存在");
        }
        // 1.3 如果同一位置绑定了同一类型的产品：不允许再重新绑定，根据dto里的参数，查询同一位置、同一产品的设备是否存在
        wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey());
        device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("该位置/老人已绑定此设备");
        }

        //2. 再去华为云IoTDA注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        AuthInfo authInfobody = new AuthInfo();
        // 准备设备的密钥
        String secret = UUID.randomUUID().toString(true);
        authInfobody.setSecret(secret);
        body.setAuthInfo(authInfobody);
        request.withBody(body);
        // 向华为云平台发请求，注册设备
        AddDeviceResponse response = client.addDevice(request);
        // 得到设备在物联网平台的id
        String iotId = response.getDeviceId();

        //3. 保存到数据库device表
        device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(iotId);
        device.setSecret(secret);
        save(device);
    }

    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //1. 先从数据库的device表里查询设备信息
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        Device device = getOne(wrapper);
        if (device == null) {
            return null;
        }

        //2. 再调用华为云的API，得到设备的状态与激活时间
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询设备信息失败");
        }

        //3. 将结果封装成VO对象
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, vo);
        vo.setBindingLocation(Long.parseLong(device.getBindingLocation()));
        //将vo里的createTime是Date类型，转换成LocalDateTime类型
        vo.setCreateTime(device.getCreateTime().toInstant().atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime());
        vo.setDeviceStatus(response.getStatus());
        //  华为云返回的时间，是0时区的时间
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime dateTime = LocalDateTime.parse(activeTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            //  将0时间区的dateTime的值，转换成东8区的LocalDateTime对象
            vo.setActiveTime(dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime());
        }

        return vo;
    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        //1. 调用华为云平台的API，查询设备的影子信息
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网-查询设备上报的数据失败");
        }

        //2. 解析查询的结果，转换成List<DeviceReportDataVo>
        List<DeviceShadowData> shadow = response.getShadow();
        if (ObjectUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        //2.1 获取数据上报的时间
        String eventTimeStr = reported.getEventTime();
        LocalDateTime dateTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        //2.2 获取上报的各属性(物模型)的数据
        Map<String,Object> properties = (Map<String, Object>) reported.getProperties();
        List<DeviceReportDataVo> voList = new ArrayList<>();
        properties.forEach((prop, value) -> {
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(prop);
            vo.setValue(value);
            vo.setEventTime(eventTime);
            voList.add(vo);
        });

        return voList;
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询设备信息失败");
        }

        return response.getServiceCapabilities();
    }

}
